package com.heima.juc.n8;

import com.heima.juc.n2.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author : leimingchao
 * @date Date : 2022年02月20日 8:06
 */
@Slf4j(topic = "c.TestAqs")
public class TestAqs {

    public static void main(String[] args) {

        MyLock lock = new MyLock();

        new Thread(() -> {
            lock.lock();

            try {
                log.debug("locking。。。");
                Sleeper.sleep(1);
            } finally {
                log.debug("lunocking。。。");
                lock.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            lock.lock();

            try {
                log.debug("locking。。。");
            } finally {
                log.debug("lunocking。。。");
                lock.unlock();
            }
        }, "t2").start();
    }
}

/**
 * 自定义锁(不可重入锁)
 */
class MyLock implements Lock {

    /**
     * 独占锁
     */
    class MySync extends AbstractQueuedSynchronizer {

        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0,1)) {
                //加上了锁,并且设置owner为当前线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        /**
         * 是否持有独占锁
         * @return
         */
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }

        public Condition newCondition() {
            return new ConditionObject();
        }
    }

    private MySync mySync = new MySync();

    /**
     * 加锁(不成功会进入等待队列)
     */
    @Override
    public void lock() {
        mySync.acquire(1);
    }

    /**
     * 加锁，可以打断，
     *      synchronized一旦加锁，就不可以打断，容易造成死锁
     *      ReentrantLock 加锁的过程中可以打断
     * @throws InterruptedException
     */
    @Override
    public void lockInterruptibly() throws InterruptedException {
        mySync.acquireInterruptibly(1);
    }

    /**
     * 尝试加锁(一次)
     * @return
     */
    @Override
    public boolean tryLock() {
        return mySync.tryAcquire(1);
    }

    /**
     *  尝试加锁，带超时时间
     * @param time
     * @param unit
     * @return
     * @throws InterruptedException
     */
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return mySync.tryAcquireNanos(1, unit.toNanos(time));
    }

    /**
     * 解锁
     */
    @Override
    public void unlock() {
        mySync.release(1);
    }

    /**
     * 创建条件变量
     * @return
     */
    @Override
    public Condition newCondition() {
        return mySync.newCondition();
    }
}
